package org.fing.edu.uy.esbadp.mechanism.monitor;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.fing.edu.uy.esbadp.core.entity.DMRegisteredService;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.fing.edu.uy.esbadp.core.interfaces.IMechanismMonitor;
import org.jboss.mx.util.MBeanServerLocator;



public class MechanismMonitorServiceOverAllServiceTime implements IMechanismMonitor {

	private static java.util.logging.Logger logger = Logger.getLogger(MechanismMonitorServiceOverAllServiceTime.class.getSimpleName());
	private final static String overallServiceTimeProcessed = "overall service time processed";
		
	@Override
	public Object getMonitorValue(DMRegisteredService registeredService) {
		
		double serviceTimeProcessed = 0;
		try{
			MBeanServer mbeanServer = MBeanServerLocator.locateJBoss();
			String counterObjectString = makeServiceCounterObjectString(registeredService.getVirtualServiceName(), registeredService.getVirtualServiceCategory(), registeredService.getEsbProyectName());
			ObjectName counterObjectName = new ObjectName(counterObjectString);				
			long attrMbean = (Long) mbeanServer.getAttribute(counterObjectName, overallServiceTimeProcessed);
			serviceTimeProcessed = toMilliseconds(attrMbean);
		}catch (Exception ex) {
			logger.log(Level.SEVERE, "Exception in MechanismMonitorServiceSuccess when execute getMonitorValue function. \n StackTarce => [ {0} ]",ExceptionUtils.getStackTrace(ex));
		}	
		return serviceTimeProcessed;
	}
	
	private String makeServiceCounterObjectString(String virtualServiceName, String virtualServiceCategory, String proyectName){
		String domain = "jboss.esb:";
		String counterCategory = "category=MessageCounter";
		String deployment = "deployment=" + proyectName; 	
		String serviceName = "service-name=" + virtualServiceName;
		String serviceCategory = "service-category=" + virtualServiceCategory;
		String objectString = domain + counterCategory + "," + deployment + "," + serviceCategory +","+ serviceName;
		return objectString;
	}
	
	private double toMilliseconds(long time){
		return new Double(time)/1000000;
	}
	
	
}
